package org.iteasy.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

public class BeanUtil {

    private final static Logger logger = LoggerFactory.getLogger(BeanUtil.class);

    private final static String GET = "get";
    private final static String SET = "set";

    /**
     * 对象设置值
     * @param obj
     * @param fieldName
     * @param value
     * @return
     */
    public static boolean invokSet(Object obj,String fieldName, Object value) {
        Assert.notNull(obj,"obj must be null.");
        Method method =
                ReflectionUtils.findMethod(obj.getClass(), toSetName(fieldName), new Class[] {value.getClass()});
        if (method != null) {
            try {
                method.invoke(obj, value);
                return true;
            } catch (Exception e) {
                logger.warn("");
            }
        }
        return false;
    }

    /**
     * 对象中获取属性值
     * @param obj
     * @param fieldName
     * @return
     */
    public static Object invokGet(Object obj, String fieldName) {
        Assert.notNull(obj,"obj must be null.");
        Method method = ReflectionUtils.findMethod(obj.getClass(), toGetName(fieldName));
        if (method != null) {
            try {
                return method.invoke(obj);
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 设置为null
     * @param obj
     * @param fieldName
     * @return
     */
    public static boolean invokSetNull(Object obj, String fieldName) {
        Assert.notNull(obj, "obj must not be null.");
        return invokSet(obj, fieldName, null);
    }

    /**
     * 获取set方法名
     * @param fieldName
     * @return
     */
    public static String toSetName(String fieldName) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(SET).append(StringUtils.capitalize(fieldName));
        return buffer.toString();
    }

    /**
     * 获取get方法名
     * @param fieldName
     * @return
     */
    public static String toGetName(String fieldName) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(GET).append(StringUtils.capitalize(fieldName));
        return buffer.toString();
    }


}
